package cn.hy.today;


import datastruct.TreeNode;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

class Solution_2415 {

    public TreeNode reverseOddLevels(TreeNode root) {
        Deque<TreeNode> q = new ArrayDeque<>();
        q.offer(root);
        for (int i = 0; !q.isEmpty(); i++) {
            int size = q.size();
            List<TreeNode> list = new ArrayList<>();
            for (int j = 0; j < size; j++) {
                TreeNode node = q.pop();
                if (i % 2 == 1) {
                    list.add(node);
                }
                if (node.left != null) {
                    q.offer(node.left);
                    q.offer(node.right);
                }
            }
            // 交换节点值
            for (int l = 0, r = list.size() - 1; l < r; l++, r--) {
                int tmpVal = list.get(l).val;
                list.get(l).val = list.get(r).val;
                list.get(r).val = tmpVal;
            }
        }
        return root;
    }
}